﻿using IDotNet.Nssm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NLog;

namespace ConsoleAppTest
{
    class Program
    {
        private static volatile bool IsRunning = true;
        private static readonly ILogger _logger = LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            try
            {
                _logger.Info($"main start...");
                NssmServiceManager.RegisterShutdownConsoleEvent();
                NssmServiceManager.ServiceStopHandler += NssmServiceManager_ServiceStopHandler;

                for (int i = 0; i < 100; i++)
                {
                    new Thread((state) =>
                    {
                        var seq = (int) state;
                        NssmServiceManager.IncrementRunningThreadCount();
                        while (IsRunning)
                        {
                            _logger.Trace($"task{seq} {DateTime.Now.ToString()}...");
                            Thread.Sleep(15000);
                        }
                        _logger.Info($"task {seq} end...");
                        NssmServiceManager.DecrementRunningThreadCount();
                    }).Start(i);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"Exception");
            }
            _logger.Warn($"main end...");
            Console.WriteLine("print any key to exit...");
            Console.ReadLine();
        }

        private static Task NssmServiceManager_ServiceStopHandler()
        {
            IsRunning = false;
            return Task.CompletedTask;
        }
    }
}
